<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="资产名称" prop="assetName">
            <el-input v-model="formData.assetName" placeholder="请输入资产名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资产编码" prop="assetSn">
            <el-input v-model="formData.assetSn" disabled placeholder="资产编码自动生成" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="品牌" prop="assetBrand">
            <el-input v-model="formData.assetBrand" maxlength="50" placeholder="请输入品牌" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="型号" prop="assetModel">
            <el-input v-model="formData.assetModel" maxlength="50" placeholder="请输入型号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="资产分类" prop="categoryId">
            <el-tree-select
              v-model="formData.categoryId"
              :data="categoryList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              placeholder="请选择资产分类"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资产状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.BMS_ASSET_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否进口" prop="isImport">
            <el-select v-model="formData.isImport" placeholder="请选择">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.BMS_ASSET_IMPORT)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="购买方" prop="purchaser">
            <el-select v-model="formData.purchaser" placeholder="请选择">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.BMS_ASSET_PURCHASER)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="申报科室" prop="department">
            <el-input v-model="formData.department" maxlength="50" placeholder="请输入申报科室" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="安装位置" prop="location">
            <el-input v-model="formData.location" maxlength="50" placeholder="请输入安装位置" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="单价" prop="price">
            <el-input v-model="formData.price" placeholder="请输入单价" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供货商" prop="supporter">
            <el-input v-model="formData.supporter" maxlength="50" placeholder="请输入供货商" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contact">
            <el-input v-model="formData.contact" placeholder="请输入联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="tel">
            <el-input v-model="formData.tel" maxlength="50" placeholder="请输入联系方式" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="购买时间" prop="purchaseTime">
            <el-date-picker
              v-model="formData.purchaseTime"
              clearable
              placeholder="请选择购买时间"
              type="date"
              value-format="x"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import * as AssetApi from '@/api/bms/asset'
import { CategoryApi } from '@/api/eiot/category'
import { FormRules } from 'element-plus'

defineOptions({ name: 'AssetForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  assetName: '',
  categoryId: '',
  assetBrand: '',
  assetModel: '',
  type: undefined,
  status: undefined,
  isImport: undefined,
  purchaser: undefined,
  department: '',
  location: '',
  price: undefined,
  purchaseTime: '',
  supporter: '',
  contact: '',
  tel: ''
})
const formRules = reactive<FormRules>({
  assetName: [{ required: true, message: '资产名称不能为空', trigger: 'blur' }],
  assetBrand: [{ required: true, message: '品牌不能为空', trigger: 'blur' }],
  assetModel: [{ required: true, message: '型号不能为空', trigger: 'blur' }],
  department: [{ required: true, message: '申报科室不能为空', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择产品分类', trigger: 'change' }],
  type: [{ required: true, message: '请选择资产类型', trigger: 'change' }],
  status: [{ required: true, message: '请选择资产状态', trigger: 'change' }],
  isImport: [{ required: true, message: '请选择是否进口', trigger: 'change' }],
  purchaser: [{ required: true, message: '请选择购买方', trigger: 'change' }],
  price: [
    { required: true, message: '单价不能为空', trigger: 'blur' },
    { type: 'number', message: '单价必须为数字值' }
  ]
})
const formRef = ref() // 表单 Ref
const categoryList = ref<Tree[]>([]) // 树形结构

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AssetApi.getAsset(id)
    } finally {
      formLoading.value = false
    }
  }
  // 加载产品分类树
  categoryList.value = handleTree(await CategoryApi.getSimpleCategoryList())
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AssetApi.AssetVO
    if (formType.value === 'create') {
      await AssetApi.createAsset(data)
      message.success(t('common.createSuccess'))
    } else {
      await AssetApi.updateAsset(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    assetName: '',
    categoryId: '',
    assetBrand: '',
    assetModel: '',
    type: undefined,
    status: undefined,
    isImport: undefined,
    purchaser: undefined,
    department: '',
    location: '',
    price: undefined,
    purchaseTime: '',
    supporter: '',
    contact: '',
    tel: ''
  }
  formRef.value?.resetFields()
}
</script>
